<template>
  <div class="upload-file">
    <el-upload class="upload-demo" drag :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="fileList" :limit="1" :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess" :show-file-list="false" :headers="headers" ref="upload" accept=".jpg,.jpeg,.png,image/jpeg,image/png">
      <div class="upload-content">
        <i class="el-icon-upload"/>
        <div class="upload-text">{{ $t('imgUpload.dragAndDrop') }}<em>{{ $t('fileUpload.clickToUpload') }}</em></div>
        <div v-if="showTip" class="upload-tip">{{ $t('imgUpload.uploadTip', { fileSize: fileSize }) }}</div>
      </div>
    </el-upload>
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <div class="image-thumbnail">
          <i class="el-icon-picture-outline image-icon"/>
          <span class="image-text">{{ $t('imgUpload.imageFile') }}</span>
        </div>
        <el-link :href="`${baseUrl}${file.url}`" :underline="false" target="_blank">
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger">{{ $t('common.delete') }}</el-link>
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  name: "ImgUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 500,
    },
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      baseUrl:process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/iot/tool/uploadImg",
      headers: {Authorization: "Bearer " + getToken(),},
      fileList: [],
      loadingMessage: null // 存储加载消息实例
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          const list = Array.isArray(val) ? val : this.value.split(',');
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    showTip() {return this.isShowTip && this.fileSize;},
  },
  methods: {
    handleBeforeUpload(file) {
      const allowedTypes = ['image/jpeg', 'image/png'];
      const fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1).toLowerCase();
      const allowedExtensions = ['jpg', 'jpeg', 'png'];
      if (!allowedTypes.includes(file.type) && !allowedExtensions.includes(fileExtension)) {
        this.$message.error(this.$t('imgUpload.fileTypeError'));
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(this.$t('fileUpload.fileSizeError', { fileSize: this.fileSize }));
          return false;
        }
      }
      const uploadingFile = {
        name: file.name,
        uid: file.uid,
        uploading: true
      };
      this.fileList = [uploadingFile];
      this.loadingMessage = this.$message({
        message: `<strong style="color: #f56c6c; font-weight: bold;">${this.$t('fileUpload.uploading')}</strong>`,
        type: 'info',
        duration: 0,
        showClose: true,
        dangerouslyUseHTMLString: true
      });
      return true;
    },
    handleUploadProgress(event, file, fileList) {
      // 更新对应文件的进度
      const fileIndex = this.fileList.findIndex(f => f.uid === file.uid);
      if (fileIndex !== -1) {
        this.$set(this.fileList[fileIndex], 'progress', Math.floor(event.percent));
      }
    },
    handleExceed() {
      this.$message.error(this.$t('imgUpload.onlyOneFile'));
    },
    handleUploadError(err, file, fileList) {
      // 关闭加载消息
      if (this.loadingMessage) {
        this.loadingMessage.close();
        this.loadingMessage = null;
      }
      const fileIndex = this.fileList.findIndex(f => f.uid === file.uid);
      if (fileIndex !== -1) {
        this.fileList.splice(fileIndex, 1);
      }
      this.$message.error(this.$t('imgUpload.uploadFailed'));
    },
    handleUploadSuccess(response, file, fileList) {
      // 关闭加载消息
      if (this.loadingMessage) {
        this.loadingMessage.close();
        this.loadingMessage = null;
      }
      this.fileList = [{ name: response.fileName, url: response.fileName }];
      this.$emit("input", this.listToString(this.fileList));
      this.$message.success(this.$t('fileUpload.uploadSuccess'));
    },
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>

<style scoped lang="scss">
.upload-demo {
  .el-upload {
    display: block;
    .el-upload-dragger {
      width: 100%;
    }
  }
  .el-upload__tip {
    margin-top: 10px;
    text-align: center;
    color: #606266;
  }
  .upload-content {
    .el-icon-upload {
      font-size: 67px;
      color: #c0c4cc;
      margin-bottom: 16px;
    }
    .upload-text {
      color: #606266;
      font-size: 14px;
      em {
        color: #409EFF;
        font-style: normal;
      }
    }
    .upload-tip {
      color: #909399;
      font-size: 12px;
      margin-top: 7px;
    }
  }
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  align-items: center;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
  width: 100%;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
.image-thumbnail {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  min-width: 80px;
}
.image-icon {
  font-size: 24px;
  color: #409EFF;
  margin-bottom: 5px;
}
.image-text {
  font-size: 12px;
  color: #606266;
}
</style>
